import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// 创建实例
const request = axios.create({
  // baseURL: 'http://localhost:8080/api',
  baseURL: 'http://139.224.189.153:3007/api',
  timeout: 5000
})

// axios的请求拦截器
request.interceptors.request.use(
  config => {
    // 如果已经登录,存在token
    if (store.getters.token) {
      config.headers.Authorization = store.getters.token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// axios的响应拦截器
request.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 查看状态码判断错误
    if (error?.response?.status === 401) {
      Message({
        message: '身份认证失败,请重新登录',
        type: 'error',
        duration: 3 * 1000
      })
      // token过期
      // 1.清除token 2.清除用户信息 3.返回登录页面
      store.dispatch('user/logoutActions')
      router.replace(`/login?redirect=${encodeURIComponent(router.currentRoute.fullPath)}`)
    }
    return Promise.reject(error)
  }
)

export default request
